package icu.wdm.flinkcdc.mysql;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class RefCountedReentrantLock {
    private final ReentrantLock lock;
    private final AtomicInteger refCount;

    public RefCountedReentrantLock() {
        this.lock = new ReentrantLock();
        this.refCount = new AtomicInteger(0);
    }

    public synchronized void lock() {
        lock.lock();
        refCount.incrementAndGet();
    }

    public synchronized void unlock() {
        if (refCount.decrementAndGet() == 0) {
            lock.unlock();
        }
    }

    public boolean isLocked() {
        return refCount.get() > 0;
    }
}